package com.hl.sfzy.log;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.hl.sfzy.entity.WebLog;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;

@Aspect
@Component
@Order(1)
@Slf4j
/**
 * Controller统一日志配置
 */
public class WebLogAspect {

    static {
        System.err.println("helo");
    }

    public WebLogAspect() {
        System.out.println("hello2");
    }

    @Pointcut("execution(public * com.hl.sfzy.controller.*.*(..))")
    public void weblog() {
    }

    @Before("weblog()")
    public void doBefore() {
    }

    @After("weblog()")
    public void doAfter() {
    }

    @Around("weblog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        System.err.println("helo");
        long timeMillis = System.currentTimeMillis();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        WebLog webLog = new WebLog();
        Object proceed = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        String urlStr = request.getRequestURL().toString();
        webLog.setBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
        webLog.setUsername(request.getRemoteUser());
        webLog.setMethod(request.getMethod());
        webLog.setResult(proceed);
        webLog.setSpendTime((int) (endTime - timeMillis));
        webLog.setStartTime(timeMillis);
        webLog.setUri(request.getRequestURI());
        webLog.setUrl(request.getRequestURL().toString());
        Map<String, Object> logMap = new HashMap<>();
        logMap.put("url", webLog.getUrl());
        logMap.put("method", webLog.getMethod());
        logMap.put("parameter", webLog.getParameter());
        logMap.put("spendTime", webLog.getSpendTime());
        logMap.put("description", webLog.getDescription());
        String logInfo = String.format(
                "Web Log: URL=%s, Method=%s, IP=%s, Username=%s, SpendTime=%d ms, Description=%s",
                webLog.getUrl(), webLog.getMethod(), webLog.getIp(), webLog.getUsername(), webLog.getSpendTime(),
                webLog.getDescription());
        log.info("\u001B[32m" + logInfo + "\u001B[0m");
        return proceed;

    }
}
